package com.nikmesoft.android.referendumfriend.activities;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.nikmesoft.android.referendumfriend.R;
import com.nikmesoft.android.referendumfriend.adapters.Activity_adapter;
import com.nikmesoft.android.referendumfriend.models.ItAptMyAc;
import com.nikmesoft.android.referendumfriend.models.ItemMyActivities;
import com.nikmesoft.android.referendumfriend.models.MyActivities;
import com.nikmesoft.android.referendumfriend.service.LoginHandler;
import com.nikmesoft.android.referendumfriend.utils.CommonUtil;

public class Activity1 extends BaseActivity implements OnItemClickListener {
	private ListView myListView;
	String t = "Group: ";
	private Activity_adapter adapter;
	TextView check;
	private TextView hoobycurrent;
	private int REQUEST_CODE = 100;
	private int REQUEST_CODE1 = 101;
	private int REQUEST_CODE2 = 102;
	TextView poststatus;
	TextView nameGroup;
	MyActivities myacti;
	private ProgressDialog dialog;
	private WSLoader loader;
	ArrayList<ItAptMyAc> arrayStatus = new ArrayList<ItAptMyAc>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_my_activities);
		poststatus = (TextView) findViewById(R.id.post_status);
		nameGroup = (TextView) findViewById(R.id.tvNameGroup);
		myListView = (ListView) findViewById(R.id.listview);
		myListView.setDividerHeight(0);

		Bundle bun = (Bundle) getIntent().getExtras();
		myacti = (MyActivities) bun.getSerializable("myacty");

		for (int i = 0; i < myacti.getArr().size(); i++) {
			String st = myacti.get(i).getContent();
			if (st.length() > 30)
				st = st.substring(0, 29);
			arrayStatus.add(new ItAptMyAc(st, myacti.get(i).getName_hobby(),
					myacti.get(i).getLike(), myacti.get(i).getDislike(),myacti.get(i).getId()));
		}
		adapter = new Activity_adapter(this, R.layout.item, arrayStatus);
		myListView.setAdapter(adapter);
		myListView.setOnItemClickListener(this);

		dialog = new ProgressDialog(this);
		dialog.setMessage("Loading...Please wait...");
	}

	public void callBack(View v) {
		finish();
	}

	public void groupName(View v) {

	}

	public void like(View v) {
		ImageView like=(ImageView)findViewById(R.id.imageLike);
		String id_acti=(String)like.getTag();
		if (loader == null || loader.isCancelled()
				|| loader.getStatus() == Status.FINISHED) {
			loader = new WSLoader();
			loader.execute(String.valueOf(LoginHandler.result.getId()),id_acti,"1");
		}
		
		}
	public void unlike(View v) {
		ImageView unlike=(ImageView)findViewById(R.id.imageUnLike);
		String id_acti=(String)unlike.getTag();
		if (loader == null || loader.isCancelled()
				|| loader.getStatus() ==  Status.FINISHED) {
			loader = new WSLoader();
			loader.execute(String.valueOf(LoginHandler.result.getId()),id_acti,"-1");
		}
		}

	public void callAdd(View v) {
		Intent intent = new Intent(this, Activity_addstt.class);
		startActivityForResult(intent, REQUEST_CODE1);
	}

	public void backhome(View v) {
		finish();
	}

	public void myhobby(View v) {
		Intent intent = new Intent(this, Group.class);
		startActivityForResult(intent, REQUEST_CODE);
	}
public void toad(String s)
{
CommonUtil.toastNotify(this,s);	
}
	private Void callWS_FB(String id_user, String id_activity, String action) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+ "<addFB soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "<AddFBRequest xsi:type=\"rdf:AddFBRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
				+ "<id_user xsi:type=\"xsd:int\">"+id_user+"</id_user>"
				+ "<id_activity xsi:type=\"xsd:int\">"+id_activity+"</id_activity>"
				+ "<action xsi:type=\"xsd:int\">"+action+"</action>"
				+ "</AddFBRequest>"
				+ "</addFB>"
				+ "</soapenv:Body>"
				+ "</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		Void a=null;
		return a;
	}

	private class WSLoader extends AsyncTask<String, Integer, Void> {

		@Override
		protected Void doInBackground(String... params) {
			return callWS_FB(params[0], params[1], params[2]);

		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				String name = data.getStringExtra("name");
				hoobycurrent.setText(name);
			}
		}

	}

	public void onItemClick(AdapterView<?> arg0, View view, int position,
			long arg3) {

		Intent intent = new Intent(this, MyActivities_detail.class);
		Bundle bun = new Bundle();
		ItemMyActivities it = new ItemMyActivities();
		it = myacti.get(position);
		bun.putSerializable("mydetail", it);
		intent.putExtras(bun);
		startActivity(intent);

	}

}
